<template>
  <div class="main-div">
    <el-card class="login-card" shadow="hover">
      <div style="display: flex;flex-direction: column;align-items: center">
        <div v-show="loginTag === 0">
          <div style="display: flex;flex-direction: row;align-items: center; font-weight: bold;font-size: 20px;">
            <el-image src="/image/booking-icon.png" style="width: 50px;height: 50px"></el-image>
            <text style="margin-left: 30px;font-size: 28px;color: #20a0ff">设备预约系统</text>
          </div>
          <div style="margin-top: 40px;width: 450px">
            <el-form
                label-position="top"
                label-width="auto"
                :model="formLogin"
                style="max-width: 600px"
            >
              <el-form-item label="邮箱">
                <el-input placeholder="请输入邮箱账号" clearable v-model="formLogin.name" style="height: 40px"/>
              </el-form-item>
              <el-form-item label="密码">
                <el-input placeholder="请输入密码" type="password" show-password clearable
                          v-model="formLogin.password" style="height: 40px"/>
              </el-form-item>
              <el-form-item label="验证码">
                <el-input placeholder="请输入验证码" clearable maxlength="4"
                          show-word-limit
                          v-model="formLogin.code" style="height: 40px;width: 200px"/>
                <el-image @click="refreshCodeClick" style="width: 100px;margin-left: 20px" :src="captchaUrl"/>
              </el-form-item>
            </el-form>
          </div>
          <!--          <div-->
          <!--              style="display: flex;flex-direction: row;align-items: center;justify-content: space-between;margin-top: 5px">-->
          <!--            <text></text>-->
          <!--            <el-checkbox v-model="adminTag">管理员</el-checkbox>-->
          <!--          </div>-->
          <div
              style="width: 450px; display: flex;flex-direction: row;align-items: center;justify-content: space-between;margin-top: 5px">
            <el-button
                @click="resetClick"
                type="warning"
                link
            >忘记密码?
            </el-button
            >

            <el-button
                @click="regClick"
                type="warning"
                link
            >马上注册>>
            </el-button
            >
          </div>
          <el-button v-loading="loading" :disabled="loading" @click="loginClick"
                     style="width: 420px;height: 40px;margin-top: 30px;margin-bottom: 30px"
                     type="primary">登陆
          </el-button>
        </div>
        <div v-show="loginTag === 1">
          <div style="font-weight: bold;font-size: 26px;margin-top: 40px">注册</div>
          <div
              style="display: flex;flex-direction: row;align-items: center;justify-content: space-between;margin-top: 20px">
            <text></text>
            <el-button
                @click="backLogin"
                type="warning"
                link
            >去登录>>
            </el-button
            >
          </div>

          <div style="margin-top: 40px;width: 450px">
            <el-form
                label-position="top"
                label-width="auto"
                :model="formReg"
                :rules="rules"
                style="max-width: 600px"
            >
              <el-form-item label="邮箱">
                <el-input placeholder="请输入邮箱账号" clearable v-model="formReg.name"/>
              </el-form-item>

              <el-form-item label="姓名">
                <el-input placeholder="请输入姓名" clearable v-model="formReg.nickname"/>
              </el-form-item>

              <el-form-item label="手机号">
                <el-input placeholder="请输入正确的手机号" clearable v-model="formReg.phone"/>
              </el-form-item>


              <el-form-item label="身份证号">
                <el-input placeholder="请输入正确的身份证号" clearable v-model="formReg.idCard"/>
              </el-form-item>

              <el-form-item label="学校（单位）">
                <el-input placeholder="请输入学校（单位）" clearable v-model="formReg.location"/>
              </el-form-item>

              <el-form-item label="密码">
                <el-input placeholder="请输入新密码" type="password" show-password clearable
                          v-model="formReg.password1"/>
              </el-form-item>
              <el-form-item label="重复密码 ">
                <el-input placeholder="请再输入一遍新密码" type="password" show-password clearable
                          v-model="formReg.password2"/>
              </el-form-item>
            </el-form>

            <el-button @click="toRegister" style="width: 420px;height: 40px;margin-top: 50px;margin-bottom: 30px"
                       type="primary">注册
            </el-button>
          </div>
        </div>
        <div v-show="loginTag === 2">
          <div style="font-weight: bold;font-size: 26px;">重置密码</div>
          <div style="margin-top: 40px;width: 450px">
            <el-form
                label-position="top"
                label-width="auto"
                :model="formLogin"
                style="max-width: 600px"
            >
              <el-form-item label="注册邮箱">
                <div style="display: flex;flex-direction: row;align-items: center;justify-content: space-between">
                  <el-input placeholder="请输入要找回密码的邮箱" style="width: 316px" clearable v-model="reset.name"/>
                  <el-button style="margin-left: 3px;width: 130px" type="primary" @click="sendVerificationCode"
                             :disabled="isSending">{{
                      countdown > 0 ? countdown + 's 后可重发' : '发送验证码'
                    }}
                  </el-button>
                </div>
              </el-form-item>
              <el-form-item label="验证码">
                <el-input placeholder="请输入验证码" clearable
                          v-model="reset.vCode"/>
              </el-form-item>
              <el-form-item label="新密码">
                <el-input placeholder="请输入新密码" type="password" show-password clearable
                          v-model="reset.newPwd"/>
              </el-form-item>
            </el-form>
          </div>
          <div style="display: flex;flex-direction: row;align-items: center;justify-content: space-between">
            <text></text>
          </div>
          <div
              style="width: 450px; display: flex;flex-direction: row;align-items: center;justify-content: space-between ">
            <el-button
                type="warning"
                link
            >
            </el-button
            >

            <el-button
                @click="logNowClick"
                type="warning"
                link
            >去登陆>>
            </el-button
            >
          </div>
          <el-button v-loading="loading" :disabled="loading" @click="resetSubmitClick"
                     style="width: 420px;height: 40px;margin-top: 30px;margin-bottom: 30px"
                     type="primary">重置
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>

import {ref, onMounted, onBeforeUpdate, watch, reactive} from 'vue'
import {login, checkT, register, addSubmit, resetPwd, getAuthCodePic, verifyCaptcha} from '@/api/sys'
import {useStore} from 'vuex'
import router from '../../router'
import {decrypt} from '@/utils/secret'
// 使用CryptoJS进行AES加密
import CryptoJS from 'crypto-js';
import {encrypt} from '@/utils/secret'


const store = useStore()
const loginTag = ref(0)
const regDialog = ref(false)
const adminDialog = ref(false)
const loading = ref(false)
const adminLogin = ref(false)
const isSending = ref(false)
const countdown = ref(0)
// const adminTag = ref(false) // 管理员登录
const captchaUrl = ref('')
const keys = ref('')
const formLogin = ref({
  name: '',
  password: '',
  code: ''
})
const formReg = ref({
  name: '',
  nickname: '',
  password1: '',
  password2: '',
  phone: '',
  idCard: '',
  location: ''
})
const reset = ref({
  name: '',
  vCode: '',
  newPwd: ''
})

// 定义校验规则
const rules = {
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ]
}


onMounted(() => {
  console.log('onMounted')
  //拿到验证码
  fetchCaptcha()
})

const refreshCodeClick = () => {
  //点击刷新二维码
  fetchCaptcha()
}

const fetchCaptcha = async () => {
  // const result = await register({
  let res = await getAuthCodePic()
  // console.log('res=  ', res)
  keys.value = res.keys
  captchaUrl.value = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(res.captcha)))
}

const checkVerifyCaptcha = async (keys, captcha) => {
  let res = await verifyCaptcha({
    keys,
    captcha,
  })
  return res;
  console.log('验证图形验证码的反馈：', res)
}

//重置密码
const regClick = () => {
  loginTag.value = 1
}

//进入重置密码界面
const resetClick = () => {
  console.log('密码重置')
  loginTag.value = 2
}

const backLogin = () => {
  loginTag.value = 0
}

//重置到登陆界面
const logNowClick = () => {
  loginTag.value = 0
}


const loginClick = async () => {


  if (formLogin.value.code === '' || formLogin.value.code === null) {
    ElNotification({
      title: 'Warning',
      message: '未填写验证码',
      type: 'warning',
    })
  }
  let res = await checkVerifyCaptcha(keys.value, formLogin.value.code)

  if (res.success) {
    console.log('验证成功')
    //触发登录接口
    loading.value = true
    let account = encrypt(formLogin.value.name)
    let secret = encrypt(formLogin.value.password)

    const result = await login({
      account,
      secret
    })

    console.log('login-result =  ', result)
    if (result.data.token !== '' && result.data.token !== undefined) {
      ElNotification({
        title: 'Success',
        message: ' 登录成功',
        type: 'success',
        duration: 1000,
        onClose: () => {
          loading.value = false
          regDialog.value = false
          store.commit('user/setToken', result.data.token)
          store.commit('user/setUserInfo', account)
          store.commit('user/setUserId', decrypt(result.data.id))
          store.commit('user/setUserName', decrypt(result.data.name))
          store.commit('user/setUserAdmin', decrypt(result.data.admin))
          // 在组件中调用 window.location.reload() 来刷新当前页面
          console.log('result= ', result)
          console.log('result.admin= ', result.admin)
          if (decrypt(result.data.admin) >= 1) {
            router.push('/equipment/main')
          } else {
            router.push('/home')
          }
        }
      })
    } else {
      loading.value = false
    }
  } else {
    console.log('验证失败')
    ElNotification({
      title: 'Warning',
      message: '验证码错误，请重新输入',
      type: 'warning',
    })
    //验证失败刷新验证码
    refreshCodeClick()
  }
}


//注册提交
const toRegister = async () => {
  //注册请求
  let normalEmail = formReg.value.name
  let email = encrypt(formReg.value.name)
  let nickname = encrypt(formReg.value.nickname)
  let password1 = encrypt(formReg.value.password1)
  let password2 = encrypt(formReg.value.password2)
  let phone = encrypt(formReg.value.phone)
  let idcard = encrypt(formReg.value.idCard)
  let location = encrypt(formReg.value.location)
  const result = await register({
    email,
    nickname,
    password1,
    password2,
    phone,
    idcard,
    location
  })
  // //console.log(result)
  if (result.error_code === 0) {
    //提醒注册成功
    ElNotification({
      title: 'Success',
      message: '注册成功，请登陆',
      type: 'success'
    })
    //携带用户名 跳转登陆界面
    loginTag.value = 0
    formLogin.value.name = normalEmail
  }
}


//提交重置密码
const resetSubmitClick = async () => {
  console.log('提交重置的密码')
  if (reset.value.name === '') {
    ElMessage.error('邮箱地址不能为空！')
    return
  }
  if (reset.value.vCode === '') {
    ElMessage.error('验证码不能为空！')
    return
  }

  let result = await verifyCode({
    codeToVerify: reset.value.vCode
  })

  if (result.success === false) {
    ElMessage.error('验证失败，请输入正确的验证码')
  } else {
    if (reset.value.newPwd === '') {
      ElMessage.error('未填写新密码!')
    } else {
      console.log('验证通过，重置密码操作')
      let result = await resetPwd({
        email: reset.value.name,
        newPassword: reset.value.newPwd
      })
      console.log('重制密码的返回：', result)
    }
  }
  console.log('验证码验证返回= ', result)
}


// 模拟发送验证码和倒计时的逻辑
async function sendVerificationCode() {
  if (isSending.value) return // 如果正在发送，则直接返回
  if (reset.value.name === '') {
    ElMessage.error('邮箱不能为空！')
    return
  }

  // 模拟发送验证码的异步操作
  isSending.value = true // 设置发送状态为 true
  countdown.value = 60 // 设置倒计时为 60 秒

  // 开始倒计时
  const intervalId = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value-- // 每秒减一
    } else {
      clearInterval(intervalId) // 倒计时结束，清除定时器
      isSending.value = false // 重置发送状态为 false
    }
  }, 1000)

  // 在这里你可以添加发送验证码到服务器的逻辑
  let result = await sendVcode({
    email: reset.value.name
  })

  console.log('code result =   ', result)

  if (result.success === true) {
    ElMessage.success('验证码已发送，请去邮箱查收！')
  } else {
    ElMessage.error('验证码发送失败，请稍后再试')
  }
}


</script>

<style lang='scss' scoped>

.main-div {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-size: 100% 100%;
  background-image: url("../../../public/image/bg.jpg");
}

.login-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 850px;
  height: 850px;
}

</style>
